const userDao = require('../dao/userDao')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const config = require('../config/config.js')
const utils = require('../utils/utils')

// 用户注册
exports.register = async ctx => {
  let body = ctx.request.body
  body.avatar = 'https://images.nowcoder.com/head/675m.png?x-oss-process=image/resize,m_mfit,h_100,w_100'
  // body.avatar = 'https://www.dmoe.cc/random.php'
  body.username = '用户' + utils.randomID()
  const isRegister = await userDao.findByAccount(body);
  // const socketID = await userDao.findBySocketID(body);
  if (isRegister) return ctx.warning('该账号已被注册')
  // if(socketID){
  //   ctx.warning('socketID重复,请刷新后重试')
  //   return
  // }
  body.password = md5(body.password)
  await userDao.create(body);
  ctx.success('注册成功')
}

// 用户登录
exports.login = async ctx => {
  let body = ctx.request.body
  let res = await userDao.findByAccount(body);
  if(!res){
    ctx.warning('账号不存在')
    return 
  }
  let { id,account,password,username } = res  
  if (body.account === account && md5(body.password) === password) {
    let {
      secretKey,
      expiresIn
    } = config.security
    let payload = {
      id: id,
      account: account,
      username: username
    }
    let token = jwt.sign(payload, secretKey, {
      expiresIn: expiresIn
    });
    ctx.success('登录成功',token)
  } else {
    ctx.warning('密码错误')
  }
}

// 获取个人信息
exports.getUserInfo = async ctx => {
  let token = ctx.request.headers["authorization"];
  let payload = jwt.verify(token,config.security.secretKey)
  const userInfo = await userDao.findById(payload);
  ctx.success('',userInfo)
}

// 获取所有用户信息
exports.getAllUser = async ctx => {
  let { p = 1,limit = 10 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await userDao.findAll(body);
  ctx.success('',res)
}

// 获取所有医生信息
exports.getAllDoctor = async ctx => {
  let body = '1'
  const res = await userDao.findAllByRole(body);
  ctx.success('',res)
}

// 根据用户名 账号 医院模糊搜索用户
exports.searchUser = async ctx => {
  let { username } = ctx.request.query
  let res = await userDao.getUserByField(username)
  ctx.success('',res)
}

// 更新数据
exports.updUserInfo = async ctx => {
  let body = ctx.request.body
  let res = await userDao.upd(body);
  ctx.success('更新成功')
}